package com.hjt.datastructures.queue;

import java.lang.reflect.Array;

/**
 * @Author: huangjiantao
 * @Date: 2021-08-23 20:02
 * 环形数组队列小Demo
 * <p>
 * 疑问：在该环形数组中存放三个值之后，取出一个值之后，在往里面添加一个值，在数组中有四个值？？
 */
public class CircleArrayQueueDemo {
    public static void main(String[] args) {
        CircleArrayQueue circleArrayQueue = new CircleArrayQueue(4);
        circleArrayQueue.add(10);
        circleArrayQueue.add(20);
        circleArrayQueue.add(30);
        circleArrayQueue.show();
        System.out.println("----------------------");

        circleArrayQueue.get();
        circleArrayQueue.show();
        System.out.println("----------------------");
        circleArrayQueue.add(40);
        circleArrayQueue.show();
        System.out.println("**********************");
        int head = circleArrayQueue.head();
        System.out.println(head);
        int size = circleArrayQueue.size();
        System.out.println(size);
    }
}

class CircleArrayQueue {
    private int maxSize;//数组的最大长度
    private int front;//指向数组头部元素，初始值为0
    private int rear;//指向数组尾部的前一个元素，初始值为0，为数组预留一个空间
    int[] arr;//初始一数组

    /**
     * 构造方法
     *
     * @param cirQueueMaxsize
     */
    public CircleArrayQueue(int cirQueueMaxsize) {
        maxSize = cirQueueMaxsize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

    //判断是否为空
    public boolean isEmpty() {
        return front == rear;
    }

    //判断队列是否满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    //添加数据
    public void add(int n) {
        if (isFull()) {
            System.out.println("队列已满无法添加数据");
            return;
        }
        arr[rear] = n;//直接添加元素
        rear = (rear + 1) % maxSize;
    }

    //取出数据
    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,无法取出数据");
        }
        //将数据保存至临时变量
        //front再后移
        int value = arr[front];
        front = (front + 1) % maxSize;
        return value;
    }

    /**
     * 显示环形队列全部元素
     */
    public void show() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,无法取出数据");
        }
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d\n", i, arr[i]);
        }
    }

    //显示数组有效个数,实际个数为size+1
    public int size() {
        //maxsize=3
        //rear=0,front=0 size=0
        //rear=1,front=0 size=1
        //rear=5,front=3 size=2
        return (rear + maxSize - front) % maxSize;
    }

    //显示队列头
    public int head() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空,无法头部数据");
        }
        return arr[front];
    }
}
